import 'dart:async';
import 'dart:convert';
import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:wanxiang_app/bean/registe_entity.dart';
import '../../bean/simple_entity.dart';
import '../../utils/network_manager.dart';
import '../../utils/network_url.dart';
import '../../utils/toast_util.dart';
import '../../widgets/account_textField2.dart';
import 'dart:io';

import '../../widgets/agreement_dialog.dart';
import 'agreement.dart';



class RegisteController extends GetxController{

  @override
  void onInit() {
    super.onInit();
    // getIp();
  }
  @override
  void onClose() {
    super.onClose();
  }

  bool checked = false;

  String mobile = '';
  String code = '';
  String psw = '';
  String psw2 = '';
  String share = '';
  String ip='';

  int countTime = 60;

  changeCheck(){
    checked = !checked;
    update();
  }

  getIp() async{
    final List<InternetAddress> host = await InternetAddress.lookup('localhost', type: InternetAddressType.IPv4);
    print('ippppppp=');
    print(host[0].address);
  }

  String timeTip='获取验证码';
  late Timer _timer;
  void _countTime() {
    _timer = Timer.periodic(const Duration(milliseconds: 1000), (timer) {
      countTime--;
      if (countTime == 0) {
        _timer.cancel();
        countTime = 60;
        timeTip = '重新获取';
      } else {
        timeTip = '重新获取${countTime}S';
      }
      update();
    });
  }

   _getCode(){
    if(countTime!=60){
      return;
    }
    if(mobile.isEmpty || mobile.length<11){
      ToastUtil.show('请正确输入手机号');
      return;
    }
    DioManager.getInstance().post(ServiceUrl.loginCode,{'code_type':'1','mobile':mobile.toString()}, (data) async {
      SimpleEntity bannerEntity = SimpleEntity.fromJson(jsonDecode(data));
      if(bannerEntity.code!=200){
        ToastUtil.show(bannerEntity.msg);
      }else{
        _countTime();
      }
      update();
    }, (error) {
      ToastUtil.show(error);
    });
  }
  late BuildContext mContext ;
  void _submit(){
    if(!checked){
      showDialog(context: mContext, builder: (BuildContext context1) {
        return MyAgreemnentDialog(callBack: (String content) {
          if(content == 'cancel'){
            Navigator.pop(context1);
          }else if(content == 'sure'){
            checked = true;
            Navigator.pop(context1);
            update();
          }
        },
          cancelText: '拒绝',
          sureText: "已阅读并同意",
        );
      });
      return;
    }
    if(mobile.isEmpty){
      ToastUtil.show('请正确输入手机号');
      return;
    }

    if(code.isEmpty){
      ToastUtil.show('请输入验证码');
      return;
    }

    if(psw.isEmpty || psw.length<6 || psw.length>16){
      ToastUtil.show('请正确输入密码');
      return;
    }

    if(psw2.isEmpty || psw2.length<6 || psw2.length>16){
      ToastUtil.show('请正确输入密码');
      return;
    }

    if(psw2!=psw){
      ToastUtil.show('两次密码不一致');
      return;
    }

    DioManager.getInstance().post(ServiceUrl.registe,{
      "verifyCode":code, "password":psw, "invitationcode":share,
      "username":mobile, "userip":ip,
    }, (data) async {
      RegisteEntity bannerEntity = RegisteEntity.fromJson(jsonDecode(data));
      ToastUtil.show(bannerEntity.msg);
      if(bannerEntity.code==200){

        if(_timer!=null){
          _timer.cancel();
        }
        Get.back();
      }else{

      }
    }, (error) {
      ToastUtil.show(error);
    });
  }
}

class RegistePage extends GetView<RegisteController> {
  int type = 0;
  late RegisteController controller ;
  late BuildContext context ;

  @override
  Widget build(BuildContext context1) {

    Get.lazyPut<RegisteController>(() => RegisteController());
    controller = Get.find();
    context = context1;
    controller.mContext= context1;
    return GetBuilder<RegisteController>(
      builder: (_){
        return  Scaffold(
            backgroundColor: Colors.white,
            body:SingleChildScrollView(
              child: _content(),
            ) );
      },
    )
    ;
  }


  Widget _content() {
    return Container(
      padding: EdgeInsets.only(left: 20.w, right: 20.w),
      decoration: const BoxDecoration(
          image: DecorationImage(
        image: AssetImage('assets/images/login_bg.png'),
        fit: BoxFit.fill,
      )),
      child: Stack(
        children: [
          Column(
            children: [
              SizedBox(
                height: MediaQueryData.fromWindow(window).padding.top + 21.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: [

                  InkWell(
                    onTap: (){
                      Get.back();
                    },
                    child:  Text(
                      '去登录',
                      style: TextStyle(color: Color(0xFF333333), fontSize: 15.sp),
                    )
                  )


                ],
              ),
              SizedBox(
                height: 23.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    'HELLO!',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                        color: Color(0xFF333333),
                        fontSize: 29.sp,
                        fontWeight: FontWeight.w600),
                  )
                ],
              ),
              SizedBox(
                height: 22.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Text(
                    '欢迎来到淘号阁',
                    textAlign: TextAlign.start,
                    style: TextStyle(
                      color: Color(0xFF333333),
                      fontSize: 21.sp,
                    ),
                  )
                ],
              ),
              Container(
                margin: EdgeInsets.only(
                  top: 60.h,
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  keyboardType: TextInputType.number,
                  maxLength: 11,
                  hitText: '请输入手机号',
                  icon: 'assets/images/login_account.png',
                  contentStrCallBack: (content) {
                    controller.mobile = content;
                  }, key: ValueKey('account'),
                ),
              ),

              SizedBox(
                height: 22.h,
              ),

              Row(
                children: [
                  Container(
                    width: 203.w,
                    margin: EdgeInsets.only(

                    ),
                    child: AccountEdit2Text(
                      //获取返回的输入内容
                      hitText: '请输入验证码',
                      icon: 'assets/images/login_code.png',
                      contentStrCallBack: (content) {
                        controller.code = content;
                      }, key: ValueKey('code'),
                    ),
                  ),
                  SizedBox(
                    width: 8.w,
                  ),
                  _code()
                ],
              ),
              SizedBox(
                height: 19.h,
              ),
              Container(
                margin: EdgeInsets.only(
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  pwd:true,
                  hitText: '请输入6-16位登录密码',
                  icon: 'assets/images/login_psw.png',
                  contentStrCallBack: (content) {
                    controller.psw = content;
                  }, key: ValueKey('account'),
                ),
              ),
              SizedBox(
                height: 19.h,
              ),
              Container(
                margin: EdgeInsets.only(
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  pwd:true,
                  hitText: '请再次输入密码',
                  icon: 'assets/images/login_psw.png',
                  contentStrCallBack: (content) {
                    controller.psw2 = content;
                  }, key: ValueKey('account'),
                ),
              ),
              SizedBox(
                height: 19.h,
              ),
              Container(
                margin: EdgeInsets.only(
                ),
                child: AccountEdit2Text(
                  //获取返回的输入内容
                  hitText: '请输入邀请码',
                  icon: 'assets/images/share.png',
                  contentStrCallBack: (content) {
                    controller.share = content;
                  }, key: ValueKey('account'),
                ),
              ),
              SizedBox(
                height: 16.h,
              ),
              InkWell(
                onTap: (){
                  controller._submit();
                },
                child:  Container(
                  alignment: Alignment.center,
                  width: 300.w,
                  height: 44.h,
                  decoration: BoxDecoration(
                      color: Color(0xFFF43F50),
                      borderRadius: BorderRadius.circular(6.r)),
                  child: Text(
                    type==0?'注册并登录':'确定',
                    style: TextStyle(color: Colors.white, fontSize: 16.sp),
                  ),
                )
              )
             ,
              SizedBox(
                height: 16.h,
              ),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Checkbox(
                      value: controller.checked,
                      onChanged: (value) {
                        // print('valuevalue='+value.toString());
                        controller.changeCheck();
                      }),
                  Text(
                    '阅读并同意',
                    style: TextStyle(
                        color: Color(0xFF666666), fontSize: 13.sp),
                  ),
                  InkWell(
                      onTap: () {
                        Get.to(()=>AgreementPage(),arguments: '用户协议');
                      },
                      child: Text(
                        '《用户协议》',
                        style: TextStyle(
                            color: Color(0xFFF43F50), fontSize: 13.sp),
                      )),
                  InkWell(
                      onTap: () {
                        Get.to(()=>AgreementPage(),arguments: '隐私协议');
                      },
                      child: Text(
                        '《隐私协议》',
                        style: TextStyle(
                            color: Color(0xFFF43F50), fontSize: 13.sp),
                      )),
                ],
              )
            ],
          ),
          // Positioned(
          //     bottom: 35.h,
          //     child: Column(
          //       children: [
          //
          //       ],
          //     ))
        ],
      ),
    );
  }

  Widget _code(){
    return InkWell(
      onTap: (){
        controller._getCode();
      },
      child: Container(
        width: 89.w,
        height: 48.h,
        alignment: Alignment.center,
        decoration: BoxDecoration(
            color: Color(0xFFF43F50),
            borderRadius: BorderRadius.circular(6.r)
        ),
        child: Text(
          controller.timeTip,
          style: TextStyle(
              color: Colors.white,
              fontSize: 12.sp
          ),
        ),
      )
    ) ;
  }

}
